using System;

namespace PhillyCodeCamp.Domain.Validation
{
    public class BusinessRule<T> : IBusinessRule<T> where T : IValidation
    {
        readonly Predicate<T> matchPredicate;
        private readonly string name;
        private readonly string description;

        public BusinessRule(string name, string description, Predicate<T> matchPredicate)
        {
            this.name = name;
            this.description = description;
            this.matchPredicate = matchPredicate;
        }

        public BusinessRule(ValidationAttribute attribute, IValidation validatedObject)
        {
            name = attribute.PropertyName;
            description = attribute.Message;
            matchPredicate = delegate { return attribute.Validate(validatedObject); };
        }

        public bool IsSatisfiedBy(T item)
        {
            return matchPredicate(item);
        }

        public string Name
        {
            get { return name; }
        }

        public string Description
        {
            get { return description; }
        }

        public override bool Equals(object obj)
        {
            IBusinessRule<T> other = obj as IBusinessRule<T>;
            return (other == null ? true : this.Name.Equals(other.Name));
        }

        public override int GetHashCode()
        {
            return matchPredicate.GetHashCode() + 29 * name.GetHashCode();
        }


    }
}